

// 使用select实现多路转接
#include <iostream>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm>
#include "Socket.hpp"

//    int select(int nfds, fd_set *readfds, fd_set *writefds,
//               fd_set *exceptfds, struct timeval *timeout);

using namespace SocketModule;

class SelectServer
{
    const static int defaultfd = -1;
    const static int size = 8 * sizeof(fd_set);

public:
    SelectServer(int port) : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        for (int i = 0; i < size; i++)
            _fd_array[i] = defaultfd;

        _fd_array[0] = _listensock->Fd();
    }
    void start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 定义fd_set集合，将要管理的文件描述符添加到里面
            fd_set rfds;
            FD_ZERO(&rfds); // 清空集合

            // 将辅助数组中的文件描述符都添加到集合中，交给select管理
            int maxfd = -1;
            for (int i = 0; i < size; i++)
            {
                if (_fd_array[i] == defaultfd)
                    continue;
                if (_fd_array[i] != defaultfd)
                {
                    FD_SET(_fd_array[i], &rfds);
                }
                if (maxfd < _fd_array[i])
                {
                    maxfd = _fd_array[i];
                }
            }
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);

            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪了...";
                Dispatcher(rfds);
                break;
            }
        }
        _isrunning = false;
    }
    // 事件派发器
    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < size; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;

            if (FD_ISSET(_fd_array[i], &rfds))
            {
                if (_fd_array[i] == _listensock->Fd())
                {
                    // 新连接到来
                    Accepter();
                }
                else
                {
                    // 数据到来
                    Recver(_fd_array[i], i);
                }
            }
        }
    }
    // 链接获取
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        // 管理新连接，添加到辅助数组中
        int pos = 0;
        for (; pos < size; pos++)
        {
            if (_fd_array[pos] == defaultfd)
                break;
        }
        if (pos == size)
        {
            LOG(LogLevel::WARNING) << "select full";
            close(sockfd);
        }
        else
        {
            _fd_array[pos] = sockfd;
        }
    }
    // IO处理
    void Recver(int fd, int i)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit...";
            _fd_array[i] = defaultfd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::INFO) << "recv error";
            _fd_array[i] = defaultfd;
            close(fd);
        }
    }
    void stop()
    {
        _isrunning = false;
    }
    ~SelectServer()
    {
    }

private:
    bool _isrunning;
    std::unique_ptr<Socket> _listensock;

    int _fd_array[size]; // 辅助数组
};